package wh.ispct

import java.text.SimpleDateFormat
import java.text.MessageFormat

class LinkContentController {
	def findJson(){
		def msg = ["success":true]
		try{
			if(params.id)
				msg["content"] = LinkContent.get(params.id)
		}catch(e){
			e.printStackTrace()
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
	
    def listJson(){
		def msg = ["success":true]
		try{
			def criteria = LinkContent.createCriteria() 
			def limit = 30
			def start = 0
			if(params.limit) limit = params.limit.toInteger()
			if(params.start) start = params.start.toInteger()
			
			msg["data"] = criteria {
				if(params.menuId)
					eq('menu',Menu.get(params.menuId))
				maxResults(limit)
                firstResult(start)
				
				order("sort","asc")
				order("createTime","desc")
			}
			msg["total"] = Content.count()
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
	
	def save(){
		def msg = ["success":true]
		try{
			def df = new SimpleDateFormat("yyyy-MM-dd")
			LinkContent c = params.id ? LinkContent.load(params.id) : new LinkContent()
			bindData(c ,params,[exclude: "createTime"])
			c.createTime = df.parse(params.createTime)
			c.menu = Menu.get(params.menuId)
			if(!c.validate())
				c.errors.each {
					throw new Exception(MessageFormat.format(it.fieldError.getDefaultMessage(),it.fieldError.arguments))
				}
			c.save()
		}catch(e){
			e.printStackTrace()
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){
			msg
		}
	}
	
	def delete(){
		def msg = ["success":true]
		try{
			def content = LinkContent.get(params.id)
			if(content)
				content.delete()
		}catch(e){
			e.printStackTrace()
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}
}
